import { Routes, Route, useNavigate, useLocation } from 'react-router-dom'
import useRouterAuth from './hooks/useRouterAuth'
import useHaveToken from './hooks/useHaveToken'
import { rootRouterConfig, RoutesItems } from './rootRoute'

import { useEffect } from 'react'

const renderRoutes = (routes: RoutesItems[]) => {
  return routes.map((item: RoutesItems, index: number) => {
    if (item && item.children) {
      return (
        <Route path={item.path} element={item.element} key={index}>
          {renderRoutes(item.children)}
        </Route>
      )
    } else {
      return <Route path={item.path} element={item.element} key={index}></Route>
    }
  })
}
export const RouterChild = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const { AuthResult } = useRouterAuth(location.pathname)
  const { haveToken } = useHaveToken()
  useEffect(() => {
    if (haveToken && !AuthResult) {
      navigate('/error')
    } else if (!haveToken && location.pathname !== '/login') {
      navigate('/login')
    } 
  }, [])

  return <Routes>{renderRoutes(rootRouterConfig)}</Routes>
}
